package com.example.bankseckill.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.bankseckill.pojo.Order;
import com.example.bankseckill.pojo.SeckillOrder;
import com.example.bankseckill.pojo.SeckillProduct;
import com.example.bankseckill.pojo.User;
import com.example.bankseckill.pojo.vo.RespBean;
import com.example.bankseckill.pojo.vo.RespPageBean;
import com.example.bankseckill.service.IOrderService;
import com.example.bankseckill.service.ISeckillOrderService;
import com.example.bankseckill.service.ISeckillProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liyangjing
 * @since 2022-01-26
 */
@RestController
@RequestMapping("/bank/order")
@Api(tags = "订单模块")
public class OrderController {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private ISeckillOrderService seckillOrderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ISeckillProductService seckillProductService;
    /**
     * 用户获取自己所有的订单
     * @param currentPage
     * @param size
     * @return
     */
    @ApiOperation(value = "查询自己的所有订单")
    @RequestMapping(value = "/getMyAllOrders",method = RequestMethod.POST)
    public RespPageBean getMyAllOrders(@RequestParam(defaultValue = "1")Integer currentPage,
                                       @RequestParam(defaultValue = "10")Integer size,
                                       User user
                                       ){
        return orderService.getOrdersByUserId(currentPage,size,user);
    }

    /**
     * 用户取消自己的订单
     * 1.返回库存
     * 2.修改订单状态
     * @param orderId
     * @return
     */
    @ApiOperation(value = "用户取消秒杀订单")
    @RequestMapping(value = "/cancleOrder",method = RequestMethod.POST)
    @Transactional
    public RespBean CancleOrder(String orderId){
        Integer id = Integer.valueOf(orderId);
        Order order = orderService.getById(id);
        if(order==null){
            return RespBean.error("用户没有该订单，无法取消!");
        }
        //修改订单状态
        if(order.getStatus()!=0){
            return RespBean.error("订单已被取消或支付,请询问管理员!");
        }
        //查询到秒杀订单
        SeckillOrder seckillOrder = seckillOrderService.getOne(new QueryWrapper<SeckillOrder>().eq("order_id", order.getId()));
        //如查到的秒杀订单为空，证明 订单已经超时被自动取消
        if(seckillOrder==null){
            return RespBean.error("订单已经超时取消了!");
        }
        seckillOrder = seckillOrderService.findSecOrderById(seckillOrder.getId());
        //返回库存
        //若是未支付状态
            try {
                //修改订单状态
                order.setStatus(-1);
                orderService.updateById(order);
                //删除改用户的秒杀订单（MYsql）和（Redis）
                seckillOrderService.removeById(seckillOrder.getId());
                //redis
                redisTemplate.delete("order:"+seckillOrder.getUserId()+":"+seckillOrder.getSeckillProduct().getId());
                //返回库存redis
                redisTemplate.opsForValue().increment("seckillProducts:" + seckillOrder.getSeckillProduct().getId());
                //mysql返回库存
                seckillProductService.update( new UpdateWrapper<SeckillProduct>().setSql("stock_count = stock_count+1")
                        .eq("id", seckillOrder.getSeckillProduct().getId()));
            } catch (Exception e) {
                e.printStackTrace();
                return RespBean.error("取消订单出现异常，请联系管理员!");
            }
            return RespBean.success("取消订单成功！","取消订单成功！");
    }
}
